<template>
  <VPage>
    <VTable ref="tableRef" v-bind="tableOptions">
      <template #form="{ form }">
        <VGroup>
          <el-select v-model="form.supplier.type" style="width: 120px">
            <el-option label="sku" value="sku"></el-option>
            <el-option label="赛盒SKU" value="sai_he_sku"></el-option>
            <el-option label="自定义sku" value="custom_sku"></el-option>
            <el-option label="产品名称" value="sku_cn_title"></el-option>
          </el-select>
          <el-input v-model="form.supplier.value" placeholder="请输入" class="w-36"></el-input>
        </VGroup>
        <VGroup>
          <div class="v-group-item">日期范围</div>
          <el-date-picker
            v-model="form.dateRange.value"
            type="monthrange"
            value-format="YYYY-MM"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :clearable="false"
            style="max-width: 240px"
          />
        </VGroup>
        <VSelect v-model="form.country" :options="options.country" style="min-width: 160px" multiple collapse-tags clearable filterable placeholder="国家" />
        <VCascader v-model="form.operate_user_id" placeholder="运营人员" multiple collapse-tags filterable clearable style="min-width: 160px" />
      </template>
      <template #toolbar_btns>
        <VButton auth="/purchase/demand/sale/type" :loading="loadings.type" @click="handleBatch('type')">批量设置运输类型</VButton>
        <VImport
          auth="/purchase/demand/sale/import"
          :tableRef="tableRef"
          importUrl="/v1/purchase-demand/sale-estimate/import"
          downloadUrl="https://xc-pms.oss-cn-shenzhen.aliyuncs.com/template/sale_estimate_template.xlsx"
          class="ml-auto"
          @success="query"
        />
        <VExport auth="/purchase/demand/sale/export" mainKey="se_id" url="/v1/purchase-demand/sale-estimate/export" name="promotion_demand" :tableRef="tableRef" />
      </template>
    </VTable>
    <Chart ref="chartRef" :options="options" @success="query" />
    <Type ref="typeRef" :options="options" @success="query" />
    <VLog ref="logRef" />
  </VPage>
</template>

<script setup lang="jsx" name="Account">
import api from "./api"
import Chart from "./components/Chart"
import Type from "./components/Type"

import VImport from '@/components/VImport'
import { getOptionPms } from "@/api/public"
import { ElMessage, ElMessageBox } from "element-plus"
import XEUtils from "xe-utils"
import { onMounted } from "vue"

const baseName = "sale_estimate"
const tableRef = ref()
const logRef = ref()
const loadings = reactive({})
// 查询
const query = () => {
  tableRef?.value.query()
}

// 获取options
const options = ref({})
Promise.all([getOptionPms({ type: baseName }).then((res) => res.data), Promise.resolve({ test: [{ label: "没有数据", value: 1 }] })]).then((res) => {
  options.value = res.reduce((acc, cur) => ((acc = { ...acc, ...cur }), acc), {})
})

// 批量操作
const typeRef = ref()
const handleBatch = (name) => {
  const selection = tableRef.value.$table.getCheckboxRecords()
  if (!selection.length) {
    ElMessage.warning("请先选择行")
    return
  }
  const se_ids = selection.map((d) => d.se_id)
  const showLoading = () => (loadings[name] = true)
  const closeLoading = () => (loadings[name] = false)
  const handle = {
    type: () => {
      typeRef.value.open(se_ids)
    },
  }
  handle[name]()
}

// 单行操作
const chartRef = ref()
const handleRow = (name, row, rowIndex) => {
  const { se_id } = row
  const showLoading = () => {
    loadings[name + rowIndex] = true
  }
  const closeLoading = () => {
    loadings[name + rowIndex] = false
  }
  const handle = {
    chart: () => {
      chartRef?.value.open(se_id)
    },
    clear1: () => {
      ElMessageBox.confirm("是否清空日常？", "清空", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
      })
        .then(() => {
          api.clear({ se_id, type: 1 }).then((res) => {
            ElMessage({ type: "success", message: "操作成功" })
            query()
          })
        })
        .catch(() => {
          ElMessage({ type: "info", message: "取消操作" })
        })
    },
    clear2: () => {
      ElMessageBox.confirm("是否清空活动？", "清空", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
      })
        .then(() => {
          api.clear({ se_id, type: 2 }).then((res) => {
            ElMessage({ type: "success", message: "操作成功" })
            query()
          })
        })
        .catch(() => {
          ElMessage({ type: "info", message: "取消操作" })
        })
    },
  }
  handle[name]()
}

const update = (item, field) => {
  const { se_id, month } = item
  api.update({ se_id, month: month.replace("年", "-").replace("月", ""), [field]: item[field] }).then((res) => {
    ElMessage.success("修改成功")
  })
}

// 列表配置
onMounted(() => {
  console.log("tableRef?.value", tableRef?.value)
  // tableRef?.value.setFormField() {}
})
const startMonth = XEUtils.toDateString(new Date(), "yyyy-MM")
const endMonth = XEUtils.toDateString(XEUtils.getWhatMonth(new Date(), 4), "yyyy-MM")
const tableOptions = reactive({
  rowConfig: { height: 132 },
  showOverflow: false,
  formConfig: {
    data: {
      supplier: { type: "sku", value: "" }, // 组合
      dateRange: { type: "month", value: [startMonth, endMonth], range: true }, // 组合
    },
  },
  columns: [
    { type: "checkbox", width: 40 },
    {
      title: "图片",
      minWidth: 120,
      slots: {
        default: ({ row }) => {
          return <VImage src={row.main_img} size="100px" />
        },
      },
    },
    {
      title: "产品信息",
      minWidth: 210,
      slots: {
        default: ({ row }) => {
          return (
            <div>
              <VText title="SKU" value={row.sku} copy />
              <VText title="自定义SKU" value={row.custom_sku} copy />
              <VText title="国家" value={row.country_name} />
              <VText title="货源状态" value={row.supply_status_name} />
              <VText title="活跃度" value={row.activation_name} />
              <VText title="主仓" value={row.warehouse_name} />
            </div>
          )
        },
      },
    },
    {
      title: "运输类型/天数",
      minWidth: 140,
      slots: {
        default: ({ row }) => {
          return (
            <div>
              <VText title="类型" value={row.transport_type_name} />
              <VText title="运输天数" value={row.country_shipments} />
            </div>
          )
        },
      },
    },
    {
      title: "销量信息",
      minWidth: 120,
      slots: {
        default: ({ row }) => {
          return (
            <div>
              <VText title="7天" value={row.transit_day} />
              <VText title="7天" value={row.sale_week_num} />
              <VText title="14天" value={row.sale_weeks_num} />
              <VText title="30天" value={row.sale_thirty_num} />
              <VText title="90天" value={row.sale_ninety_num} />
              <el-button link type="primary" onClick={() => handleRow("chart", row)}>
                <i class="dk-iconfont icon-Histogram" />
              </el-button>
            </div>
          )
        },
      },
    },
    {
      title: "预估日均销量",
      minWidth: 110,
      slots: {
        default: ({ row }) => {
          return (
            <div>
              <VText title="系统" value={row.estimate_day_sale_num} />
              <VText title="运营" value={row.operate_sale_num} />
            </div>
          )
        },
      },
    },
    { title: "预计销货成本", field: "aaa", minWidth: 110 },
    {
      title: "人员信息",
      minWidth: 180,
      slots: {
        default: ({ row }) => {
          return (
            <div>
              <VText title="计划" value={row.plan_user_name} />
              <VText title="采购" value={row.purchase_user_name} />
              <VText title="运营" value={row.operate_user_name} />
              <VText title="部门" value={row.department_name} />
            </div>
          )
        },
      },
    },
    {
      title: "批量清空",
      minWidth: 120,
      slots: {
        default: ({ row, rowIndex }) => {
          return (
            <div class="nm flex flex-col items-start">
              <el-button size="small" type="danger" class="mb-2" onClick={() => handleRow("clear1", row, rowIndex)}>
                <i class="dk-iconfont icon-Delete" />
                清空日常
              </el-button>
              <el-button size="small" type="danger" onClick={() => handleRow("clear2", row, rowIndex)}>
                <i class="dk-iconfont icon-Delete" />
                清空活动
              </el-button>
            </div>
          )
        },
      },
    },
  ],
  proxyConfig: {
    autoLoad: false,
    ajax: {
      query: ({ page, form }) =>
        api.query({ ...form, ...page }).then((res) => {
          const columns =
            res.data[0]?.detail.map((d, i) => {
              const showEdit = d.month.replace("年", "-").replace("月", "") >= startMonth
              return {
                title: d.month,
                minWidth: 180,
                slots: {
                  default: ({ row, rowIndex }) => {
                    const item = row.detail[i] || {}
                    item.se_id = row.se_id
                    return (
                      <div>
                        <div class="flex items-center gap-x-2">
                          <span class="text-gray-500 whitespace-nowrap">日常: </span>
                          {showEdit ? (
                            <el-input-number
                              v-model={item.daily_sale_num}
                              controls={false}
                              min={0}
                              step={1}
                              precision={0}
                              size="small"
                              class="w-full"
                              onChange={() => update(item, "daily_sale_num")}
                            />
                          ) : (
                            item.daily_sale_num
                          )}
                        </div>
                        <div class="flex items-center gap-x-2 my-1">
                          <span class="text-gray-500 whitespace-nowrap">活动: </span>
                          {showEdit ? (
                            <el-input-number
                              v-model={item.promotion_sale_num}
                              controls={false}
                              min={0}
                              step={1}
                              precision={0}
                              size="small"
                              class="w-full"
                              onChange={() => update(item, "promotion_sale_num")}
                            />
                          ) : (
                            item.promotion_sale_num
                          )}
                        </div>
                        <VText title="总销量" value={item.total_sale_num} />
                        <VText title="实际销量" value={item.reality_sale_num} />
                        <VText title="同比" value={item.last_month + ": " + item.last_year_num} />
                      </div>
                    )
                  },
                },
              }
            }) || []
          tableRef?.value.$table.reloadColumn(tableOptions.columns.concat(columns))
          const timer = setTimeout(() => {
            tableRef?.value.updateScroll()
            clearTimeout(timer)
          }, 500)
          return res
        }),
    },
  },
})
</script>
